<template>
	<div class="goods">
    <div class="menu-wrapper" v-el:menu-wrapper>
      <ul>
        <li @click="selectMenu($index,$event)" v-for="item in goods" class="menu-item"
            :class="{'current':currentIndex === $index}">
          <span class="text border-1px">
            <span v-show="item.type>0" class="icon"
            :class="classMap[item.type]"></span>{{item.name}}
          </span>
        </li>
      </ul>
    </div>
    <div class="foods-wrapper" v-el:foods-wrapper>
      <ul>
        <li v-for="item in goods" class="food-list food-list-hook">
          <h1 class="title">{{item.name}}</h1>
          <ul>
            <li @click="selectFood(food,$event)" v-for="food in item.foods" class="food-item border-1px">
              <div class="icon">
                <img width="57" height="57" :src=food.icon>
              </div>
              <div class="content">
                <h2 class="name">{{food.name}}</h2>
                <p class="dese">{{food.description}}</p>
                <div class="extra">
                  <span class="count">月售{{food.sellCount}}份</span><span>好评率{{food.rating}}</span>
                </div>
                <div class="price">
                  <span class="now">¥{{food.price}}</span><span class="old" v-show="food.oldPrice">¥{{food.oldPrice}}</span>
                </div>
                <div class="cartcoutotrol-warpper">
                  <cartcoutotrol :food="food"></cartcoutotrol>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <shopcart v-ref:shopcart :delivery-price="seller.deliveryPrice"
      :select-foods="selectFoods" :min-price="seller.minPrice"></shopcart>
	</div>
  <food :food="selectedFood" v-ref:food></food>
</template>

<script type='text/ecmascript-6'>
  import BScroll from 'better-scroll';
  import shopcart from 'components/shopcart/shopcart';
  import cartcoutotrol from 'components/cartcoutotrol/cartcoutotrol';
  import food from 'components/food/food';
  const ERR_OK = 0;

	export default{
    props: {
      seller: {
        type: Object
      }
    },
    // 用来保存数据信息
    data() {
      return {
        goods: [],
        // 保存li高度的数组
        listHeight: [],
        // 存储商品列表滚动的一个高度 用来跟左侧一个索引来做对比
        scrollY: 0,
        // 商品详情
        selectedFood: {}
      };
    },
    computed: {
      // 使用 计算属性 来遍历 listHeight,获取li区间的范围
      currentIndex() {
        for (let i = 0; i < this.listHeight.length; i++) {
          let h1 = this.listHeight[i];
          let h2 = this.listHeight[i + 1];
          if (!h2 || (this.scrollY >= h1 && this.scrollY < h2)) {
            return i;
          };
          // console.log("这个是H1：" + h1);
          // console.log("这个是H2：" + h2);
        }
        return 0;
      },
      // 联动 跟shopcart.vue关联。 需要遍历我们的整个商品，然后用于关联
      selectFoods() {
        let foods = [];
        // 遍历整个类型
        this.goods.forEach((good) => {
          // 每个类型下面的商品
          good.foods.forEach((food) => {
            if (food.count) {
              foods.push(food);
            }
          });
        });
        return foods;
      }
    },
    // vue 的生命周期中
    created() {
      this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee'];
      this.$http.get('/api/goods').then((response) => {
        response = response.body;
        if (response.errno === ERR_OK) {
          this.goods = response.data;
          // 拿到数据之后 重新渲染高度
          this.$nextTick(() => {
            this._initScroll();
            this._calculateHeight();
          });
        }
      });
    },
    methods: {
      // 点击右边菜单列表
      selectMenu(index, event) {
        // 解决PC端的重复点击问题
        if (!event._constructed) {
          return;
        }
        // console.log(index);
        // 获取右边商品列表的 li 标签 ； 设置变量el = 右边的li ; 然后点击的时候 使用探针 的效果
        //  直接滚动到 右边 li 标签对应的菜单
        let foodList = this.$els.foodsWrapper.getElementsByClassName('food-list-hook');
        let el = foodList[index];
        this.foodScroll.scrollToElement(el, 300);
      },
      // 用来添加滚动的效果 需要配合 better-scroll 使用
      _initScroll() {
        // click: true  允许点击（移动端）；
        this.meunScroll = new BScroll(this.$els.menuWrapper, {
          click: true
        });
        // probeType: 3 类似一个探针的效果  就是检测滚动的一个位置
        this.foodScroll = new BScroll(this.$els.foodsWrapper, {
          click: true,
          probeType: 3
        });
        // pos 滚动的一个位置 给右边的滚动 添加 一个 滚动的事件
        // 用于记录滚动的一个坐标值
        // 然后将其与左边的 菜单 做映射
        this.foodScroll.on('scroll', (pos) => {
          this.scrollY = Math.abs(Math.round(pos.y));
          // console.log(this.scrollY);
        });
      },
      // 点击或者滑动右侧商品的时候，左侧菜单高亮
      _calculateHeight() {
        // 每个li的高度
        let foodList = this.$els.foodsWrapper.getElementsByClassName('food-list-hook');
        // console.log(foodList);
        // 一个临时的高度
        let height = 0;
        // 将高度追加进去
        this.listHeight.push(height);
        for (let i = 0; i < foodList.length; i++) {
          height += foodList[i].clientHeight;
          this.listHeight.push(height);
        }
      },
      // 对应下面的events
      // 就是给shopcart组件 定义一个drop的下落方法
      _drop(target) {
        // 父组件调用子组件里面的方法 目的：获取到子组件的div
        /* 优化两个动画同时运行效果 下落动画 */
        this.$nextTick(() => {
          this.$refs.shopcart.drop(target);
        });
      },
      // 点击进入商品详情
      selectFood(food, event) {
        // 解决PC端的重复点击问题
        if (!event._constructed) {
          return;
        }
        this.selectedFood = food;
        this.$refs.food.show();
      }
    },
    components: {
      shopcart,
      cartcoutotrol,
      food
    },
    // 对应的是cartcountorrol.vue里面的 派发事件
    events: {
      // 父组件接收到的子组件传来的数据
      'cart.add'(target) {
        this._drop(target);
      }
    }
  };
</script>

<style lang='stylus' rel='stylesheet/stylus'>
  @import "../../common/stylus/minxin.styl";

  .goods
    position: absolute;
    top: 174px
    bottom :46px
    width: 100%
    display :flex
    overflow :hidden
    .menu-wrapper
      flex :0 0 80px
      width: 80px
      background-color: #f3f5f7
      .menu-item
        display :table
        height: 54px
        width: 56px
        line-height :14px
        padding :0 12px
        &.current
          position: relative
          margin-top :-1px
          z-index :10
          background-color :#ffffff
          font-weight :700
          .text
            border-none()
        .icon
          display :inline-block
          vertical-align :bottom
          width: 12px
          height: 12px
          margin-right : 2px
          background-size :12px 12px
          background-repeat :no-repeat
          &.decrease
            bg-image('decrease_3')
          &.discount
            bg-image('discount_3')
          &.guarantee
            bg-image('guarantee_3')
          &.invoice
            bg-image('invoice_3')
          &.special
            bg-image('special_3')
        .text
          display :table-cell
          font-size :12px
          vertical-align :middle
          width: 56px
          border-1px(rgba(7,17,27,0.1))
    .foods-wrapper
      flex :1
      .title
        padding-left :14px
        height: 26px
        line-height :26px
        border-left :2px solid #d9dde1
        font-size :12px
        color: rgb(147,153,159)
        background :#f3f5f7
      .food-item
        display :flex
        margin :18px
        padding-bottom :18px
        border-1px(rgba(7,17,27,0.2))
        &:last-child
          border-none()
          margin-bottom :0
        .icon
          flex :0 0 57px
          margin-right :10px
          img
            border-radius :4px
        .content
          flex :1px
          .name
            margin :2px 0 8px 0
            height :14px
            font-size :14px
            color :rgb(7,17,27)
            line-height :14px
            font-weight :700
          .dese, .extra
            font-size :10px
            color :rgb(147,153,159)
            line-height :10px
          .dese
            line-height :12px
            margin-bottom :8px
          .extra
            .count
              margin-right :12px
          .price
            font-weight:700
            line-height :24px
            .now
              margin-right :8px
              font-size :14px
              color :rgb(240,20,20)
              font-weight :700
            .old
              text-decoration :line-through
              font-size :10px
              color :rgb(147,153,159)

          .cartcoutotrol-warpper
            position :absolute
            right :0px
            bottom :12px
</style>
